<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>连接测试页面</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .test-section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        button { padding: 10px 20px; margin: 5px; background: #007bff; color: white; border: none; border-radius: 3px; cursor: pointer; }
        button:hover { background: #0056b3; }
        .result { margin-top: 10px; padding: 10px; border-radius: 3px; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .info { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
    </style>
</head>
<body>
    <h1>DNS链式攻击前端 - 连接测试</h1>
    
    <div class="test-section">
        <h3>1. 加载配置文件</h3>
        <button onclick="loadConfig()">加载配置</button>
        <div id="configResult" class="result" style="display: none;"></div>
    </div>
    
    <div class="test-section">
        <h3>2. 测试服务器连接</h3>
        <button onclick="testConnection()">测试连接</button>
        <div id="connectionResult" class="result" style="display: none;"></div>
    </div>
    
    <div class="test-section">
        <h3>3. 发送测试数据</h3>
        <button onclick="sendTestData()">发送测试数据</button>
        <div id="sendResult" class="result" style="display: none;"></div>
    </div>

    <script>
        let config = null;
        
        async function loadConfig() {
            const resultDiv = document.getElementById('configResult');
            resultDiv.style.display = 'block';
            resultDiv.className = 'result info';
            resultDiv.innerHTML = '正在加载配置...';
            
            try {
                const response = await fetch('/config.json');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                config = await response.json();
                resultDiv.className = 'result success';
                resultDiv.innerHTML = `
                    <strong>配置加载成功！</strong><br>
                    目标服务器: ${config.attackChain.protocol}://${config.attackChain.targetHost}:${config.attackChain.targetPort}<br>
                    超时时间: ${config.attackChain.timeout}ms<br>
                    重试次数: ${config.attackChain.retryCount}
                `;
            } catch (error) {
                resultDiv.className = 'result error';
                resultDiv.innerHTML = `<strong>配置加载失败:</strong> ${error.message}`;
            }
        }
        
        async function testConnection() {
            if (!config) {
                alert('请先加载配置');
                return;
            }
            
            const resultDiv = document.getElementById('connectionResult');
            resultDiv.style.display = 'block';
            resultDiv.className = 'result info';
            resultDiv.innerHTML = '正在测试连接...';
            
            try {
                const baseUrl = `${config.attackChain.protocol}://${config.attackChain.targetHost}:${config.attackChain.targetPort}`;
                const testUrl = `${baseUrl}${config.attackChain.endpoints.sendAttackData}`;
                
                const testData = {
                    test: true,
                    message: "Connection test",
                    timestamp: new Date().toISOString()
                };
                
                const controller = new AbortController();
                const timeoutId = setTimeout(() => {
                    controller.abort();
                }, config.attackChain.timeout);
                
                const startTime = Date.now();
                const response = await fetch(testUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(testData),
                    signal: controller.signal
                });
                
                clearTimeout(timeoutId);
                const endTime = Date.now();
                const duration = endTime - startTime;
                
                if (response.ok) {
                    const responseText = await response.text();
                    resultDiv.className = 'result success';
                    resultDiv.innerHTML = `
                        <strong>连接测试成功！</strong><br>
                        服务器: ${baseUrl}<br>
                        状态: ${response.status}<br>
                        响应时间: ${duration}ms<br>
                        响应: ${responseText}
                    `;
                } else {
                    const errorText = await response.text();
                    resultDiv.className = 'result error';
                    resultDiv.innerHTML = `
                        <strong>连接测试失败！</strong><br>
                        服务器: ${baseUrl}<br>
                        状态: ${response.status}<br>
                        错误: ${errorText}
                    `;
                }
            } catch (error) {
                resultDiv.className = 'result error';
                console.error('连接测试错误详情:', error);
                if (error.name === 'AbortError') {
                    resultDiv.innerHTML = `<strong>连接测试超时！</strong><br>请检查网络连接或服务器状态<br>错误类型: ${error.name}`;
                } else if (error.name === 'TypeError' && error.message.includes('fetch')) {
                    resultDiv.innerHTML = `<strong>网络连接失败！</strong><br>可能是CORS问题或网络不通<br>错误: ${error.message}`;
                } else {
                    resultDiv.innerHTML = `<strong>连接测试失败:</strong><br>错误类型: ${error.name}<br>错误信息: ${error.message}`;
                }
            }
        }
        
        async function sendTestData() {
            if (!config) {
                alert('请先加载配置');
                return;
            }
            
            const resultDiv = document.getElementById('sendResult');
            resultDiv.style.display = 'block';
            resultDiv.className = 'result info';
            resultDiv.innerHTML = '正在发送测试数据...';
            
            try {
                const baseUrl = `${config.attackChain.protocol}://${config.attackChain.targetHost}:${config.attackChain.targetPort}`;
                const testUrl = `${baseUrl}${config.attackChain.endpoints.sendAttackData}`;
                
                const testData = {
                    nodes: [
                        {
                            id: 1,
                            name: "测试节点",
                            backends: 1,
                            frontendIp: "192.168.1.1",
                            backendIps: ["192.168.1.2"],
                            level: 1
                        }
                    ],
                    connections: [],
                    targetNode: {
                        ip: "10.0.0.1",
                        port: 80
                    },
                    timestamp: new Date().toISOString(),
                    attackId: "test_" + Date.now()
                };
                
                const controller = new AbortController();
                const timeoutId = setTimeout(() => {
                    controller.abort();
                }, config.attackChain.timeout);
                
                const startTime = Date.now();
                const response = await fetch(testUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(testData),
                    signal: controller.signal
                });
                
                clearTimeout(timeoutId);
                const endTime = Date.now();
                const duration = endTime - startTime;
                
                if (response.ok) {
                    const responseText = await response.text();
                    resultDiv.className = 'result success';
                    resultDiv.innerHTML = `
                        <strong>测试数据发送成功！</strong><br>
                        服务器: ${baseUrl}<br>
                        状态: ${response.status}<br>
                        响应时间: ${duration}ms<br>
                        响应: ${responseText}
                    `;
                } else {
                    const errorText = await response.text();
                    resultDiv.className = 'result error';
                    resultDiv.innerHTML = `
                        <strong>测试数据发送失败！</strong><br>
                        服务器: ${baseUrl}<br>
                        状态: ${response.status}<br>
                        错误: ${errorText}
                    `;
                }
            } catch (error) {
                resultDiv.className = 'result error';
                if (error.name === 'AbortError') {
                    resultDiv.innerHTML = `<strong>数据发送超时！</strong><br>请检查网络连接或服务器状态`;
                } else {
                    resultDiv.innerHTML = `<strong>数据发送失败:</strong> ${error.message}`;
                }
            }
        }
        
        // 页面加载时自动加载配置
        window.addEventListener('load', loadConfig);
    </script>
</body>
</html>
